using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using eShop.Business;
using ECommerce.Library.Web;
using eShop.Utility;
using System.Collections.Generic;
using eShop.Model;


public partial class myaccount_shopping_cart : SitePublicBasePage
{
    Cart _shoppingCart;

    protected void Page_Load(object sender, EventArgs e)
    {
        uccResponseMessage.Visible = false;
        if (!Page.IsPostBack)
        {
            CheckoutStepsValidate();
            LoadSession();
            BindData();
        }
    }

    protected void BindData()
    {
        if (_shoppingCart.CartItems.Count > 0)
        {
            if (_shoppingCart.CartItems.Count == 0)
            {
                rptShoppingCart.Visible = false;
            }
            else
            {
                rptShoppingCart.DataSource = _shoppingCart.CartItems;
                rptShoppingCart.DataBind();
            }
            pnlShoppingCart.Visible = true;
            pnlEmptyCart.Visible = false;
            imbCheckout.Visible = true;
        }
        else
        {
            pnlShoppingCart.Visible = false;
            pnlEmptyCart.Visible = true;
            imbCheckout.Visible = false;
            uccResponseMessage.SetFailMessage("No product in shopping cart");
        }
    }

    protected void LoadSession()
    {
        _shoppingCart = ShoppingCartManager.GetCart();

    }

    protected void rptShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            CheckBox cbxSelectAll = (CheckBox)e.Item.FindControl("cbxSelectAll");
            if (cbxSelectAll != null)
                cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + rptShoppingCart.ClientID + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }
        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            CartItem cartItem = (CartItem)e.Item.DataItem;
            if (cartItem.Product.ProductId > 0)
            {
                HiddenField hdfProductId = (HiddenField)e.Item.FindControl("hdfProductId");
                hdfProductId.Value = cartItem.Product.ProductId.ToString();

                Image imgItemImage = (Image)e.Item.FindControl("imgItemImage");
                imgItemImage.ImageUrl = ImageResizer.CheckImageMissing(cartItem.Product.ProductImageSmallThumbnail, eShop.Business.SiteSettings.NoImageSmallThumbnailUrl);

                HyperLink hlkItem = (HyperLink)e.Item.FindControl("hlkItem");
                hlkItem.NavigateUrl = cartItem.Product.ProductUrl;
                hlkItem.Text = cartItem.Product.ProductName;

                HiddenField hfStockId = (HiddenField)e.Item.FindControl("hfStockId");
                hfStockId.Value = cartItem.Stock.StockId.ToString();

                Label lblItemNumber = (Label)e.Item.FindControl("lblItemNumber");
                lblItemNumber.Text = "Item Number: " + cartItem.Product.ItemNumber;

                Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");

                lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Product.ProductPrice);

                TextBox tbxQuantity = (TextBox)e.Item.FindControl("tbxQuantity");
                tbxQuantity.Text = cartItem.Quantity.ToString();
                tbxQuantity.MaxLength = SiteUtility.MaximumQuantityLength;

                Label lblItemTotal = (Label)e.Item.FindControl("lblItemTotal");
                lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.TotalPrice);

                Button imbItemUpdate = (Button)e.Item.FindControl("imbItemUpdate");
                imbItemUpdate.CommandArgument = e.Item.ItemIndex.ToString();
            }

        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
            CartItemCollection cartItems = (CartItemCollection)rptShoppingCart.DataSource;
            Label lblSubTotal = (Label)e.Item.FindControl("lblSubTotal");
            lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItems.SubTotal);
        }
    }

    protected void rptShoppingCart_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "UpdateCart")
            {
                int rowIndex;
                if (int.TryParse(e.CommandArgument.ToString(), out rowIndex))
                {
                    RepeaterItem rptRow = rptShoppingCart.Items[rowIndex];
                    if (rptRow != null)
                    {
                        int qty, productId, stockId;
                        TextBox tbxQuantity = (TextBox)rptRow.FindControl("tbxQuantity");
                        HiddenField hdfProductId = (HiddenField)rptRow.FindControl("hdfProductId");
                        HiddenField hfStockId = (HiddenField)rptRow.FindControl("hfStockId");

                        if (tbxQuantity != null && hdfProductId != null)
                        {
                            int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
                            int.TryParse(hdfProductId.Value.ToString(), out productId);
                            int.TryParse(hfStockId.Value.ToString(), out stockId);

                            Product product = ProductManager.GetProductById(productId);

                            if (qty > 0)
                            {
                                ShoppingCartManager.UpdateProductInCart(productId, stockId, qty);
                                LoadSession();
                                BindData();
                                
                            }
                            else
                            {

                                uccResponseMessage.SetFailMessage(ApplicationMessage.ShoppingCartInvalidQuantity);
                                uccResponseMessage.Visible = true;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(ApplicationMessage.CommonFailure);
            uccResponseMessage.Visible = true;
        }
    }

    protected void imbItemRemove_Click(object sender, EventArgs e)
    {
        try
        {
            LoadSession();
            List<CartItem> removeCartItems = new List<CartItem>();
            foreach (RepeaterItem row in rptShoppingCart.Items)
            {
                if (row.ItemType == ListItemType.Item || row.ItemType == ListItemType.AlternatingItem)
                {
                    CheckBox cbxSelect = (CheckBox)row.FindControl("cbxSelect");
                    if (cbxSelect != null && cbxSelect.Checked)
                    {
                        HiddenField hdfProductId = (HiddenField)row.FindControl("hdfProductId");
                        int productId;
                        if (int.TryParse(hdfProductId.Value, out productId))
                        {
                            if (_shoppingCart.CartItems[row.ItemIndex].Product.ProductId == productId)
                            {
                                removeCartItems.Add(_shoppingCart.CartItems[row.ItemIndex]);
                            }
                        }
                    }
                }
            }


            if (removeCartItems.Count > 0)
            {
                for (int i = 0; i < removeCartItems.Count; i++)
                {
                    _shoppingCart.CartItems.Remove(removeCartItems[i]);
                }

                BindData();
            }

        }
        catch (Exception ex)
        {
            uccResponseMessage.SetFailMessage(ApplicationMessage.CommonFailure);
            uccResponseMessage.Visible = true;
        }
    }

    

    protected void imbContinueShopping_Click1(object sender, EventArgs e)
    {
        Response.Redirect(CustomSiteMap.Home);
    }

    protected void imbCheckout_Click(object sender, EventArgs e)
    {
        if (cbAcceptPolicy.Checked)
        {
            Session["check"] = null;
            Session["minAmount"] = null;
            Session["check"] = string.Empty;

            string imageUrl = string.Empty;
            if (SessionManager.IsUserLoggedIn)
            {
                SessionManager.CheckoutSteps = CheckoutSteps.PreCheckout;
                String redirectUrl = CustomSiteMap.OrderSummary;
                Response.Redirect(redirectUrl);

            }
            else
            {
                SessionManager.CheckoutSteps = CheckoutSteps.ShoppingCart;

                String redirectUrl = CustomSiteMap.PreCheckout;
                Response.Redirect(redirectUrl);
            }
        }
        else
        {
            uccResponseMessage.SetFailMessage(ApplicationMessage.ShoppingCartAcceptTermsCondition);
            uccResponseMessage.Visible = true;
        }
    }

    private void CheckoutStepsValidate()
    {

    }
}
